package com.example.yijian.edit.view.popup;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.yijian.R;
import com.example.yijian.download.DownloadProgressBar;
import com.example.yijian.edit.background.SpaceItemDecoration;
import com.example.yijian.edit.data.AssetItem;
import com.example.yijian.edit.data.ParseJsonFile;
import com.example.yijian.edit.interfaces.OnItemClickListener;
import com.example.yijian.edit.view.HorizontalSeekBar;
import com.example.yijian.utils.Utils;
import com.example.yijian.utils.asset.NvAsset;
import com.example.yijian.utils.asset.NvAssetManager;
import com.example.yijian.utils.datainfo.TimelineData;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.android.material.tabs.TabLayout;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.example.yijian.utils.StringUtils.getString;
import static com.example.yijian.utils.asset.NvAsset.AspectRatio_16v9;

public class StickerAnimationPopup extends BaseCommonPopupWindow implements NvAssetManager.NvAssetManagerListener {

    private final String TAG = "VideoAnimationPopup";
    private final String PATH_OUT_ANIMATION = "stickeranimation/out";
    private final String PATH_IN_ANIMATION = "stickeranimation/in";
    private final String PATH_PERIOD_ANIMATION = "stickeranimation/period";

    private int CATEGORY_IN_ANIMATION = 7;
    private int CATEGORY_OUT_ANIMATION = 8;
    private int CATEGORY_ANIMATION = 9;

    private TabLayout mTabAnimation;
    private RecyclerView mRvAnimationList;
    private HorizontalSeekBar stickerSeekbar;
    private ImageView ivFinish;

    private int mSelectedAniPos;
    private int mSelectedInAniPos;
    private int mSelectedOutAniPos;

    private NvAssetManager mAssetManager;
    private int[] ANIMATION = new int[]{R.string.march_in_animation, R.string.march_out_animation, R.string.combination_animation};
    private AnimationAdapter mAnimationAdapter;
    private List<AssetItem> mPeriodList = new ArrayList<>();
    private List<AssetItem> mInList = new ArrayList<>();
    private List<AssetItem> mOutList = new ArrayList<>();

    private List<NvAsset> mAssetDataList = new ArrayList<>();
    private int mAssetType = NvAsset.ASSET_ANIMATED_STICKER_IN_ANIMATION;
    private int curRatio = NvAsset.AspectRatio_1v1;

    public StickerAnimationPopup(Context context) {
        super(context);
        setContentView(R.layout.popup_animation_popup);
        initView();
        curRatio = TimelineData.instance().getMakeRatio();
        initData();
        ivFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
    }

    private void initData() {
        for (int value : ANIMATION) {
            mTabAnimation.addTab(mTabAnimation.newTab().setText(value));
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        mRvAnimationList.setLayoutManager(layoutManager);
        mAnimationAdapter = new AnimationAdapter(getContext());
//        mAnimationAdapter.setAssetList(mInList);
        mRvAnimationList.setAdapter(mAnimationAdapter);
        mRvAnimationList.addItemDecoration(new SpaceItemDecoration(0, 15));
        mAssetManager = NvAssetManager.sharedInstance();
        mAssetManager.setManagerlistener(this);
        mAssetManager.downloadRemoteAssetsInfo(mAssetType, 1, curRatio, CATEGORY_IN_ANIMATION, 1, 20);
        refreshAnimationData();
        displayTabAnimation(0);
        checkSelectedTab();
    }

    /***
     * 展示动画Tab对应的内容
     */
    private void displayTabAnimation(int pos) {
        if (mAnimationAdapter == null) {
            return;
        }
        int type;
        int selectPos = 0;
        if (pos == 0) {
            mAnimationAdapter.setAssetList(mInList);
            mAssetType = NvAsset.ASSET_ANIMATED_STICKER_IN_ANIMATION;
            selectPos = mSelectedInAniPos;
        } else if (pos == 1) {
            mAnimationAdapter.setAssetList(mOutList);
            mAssetType = NvAsset.ASSET_ANIMATED_STICKER_OUT_ANIMATION;
            selectPos = mSelectedOutAniPos;
        } else {
            mAnimationAdapter.setAssetList(mPeriodList);
            mAssetType = NvAsset.ASSET_ANIMATED_STICKER_ANIMATION;
            selectPos = mSelectedAniPos;
        }
        mAnimationAdapter.setSelectedPos(selectPos);
        mAnimationAdapter.notifyDataSetChanged();
//        if (mStickerAnimationListener != null) {
//            mStickerAnimationListener.onItemClick(selectPos, type, mAnimationAdapter.getSelectedItem());
//        }
    }

    /**
     * 检测是动画的tab按照要求显示,仅仅第一次初始化会使用
     */
    public void checkSelectedTab() {
        int selectedTabPosition = mTabAnimation.getSelectedTabPosition();
        if (mSelectedAniPos > 0 && selectedTabPosition != 2) {
            //如果设置了组合动画，但是组合动画的tab没有被选中，则选中
            TabLayout.Tab animationTab = mTabAnimation.getTabAt(2);
            if (animationTab != null) {
                animationTab.select();
            }
        } else if (mSelectedOutAniPos > 0 && mSelectedInAniPos <= 0 && selectedTabPosition != 1) {
            //如果仅仅设置了出动画动画，但是出动画的tab没有被选中，则选中
            TabLayout.Tab animationTab = mTabAnimation.getTabAt(1);
            if (animationTab != null) {
                animationTab.select();
            }
        }
    }

    /**
     * 上来初始化一次数据
     */
    private void refreshAnimationData() {
        mOutList.clear();
        mInList.clear();
        mPeriodList.clear();
        dealAssetData(NvAsset.ASSET_ANIMATED_STICKER_IN_ANIMATION, PATH_IN_ANIMATION, mInList);
        dealAssetData(NvAsset.ASSET_ANIMATED_STICKER_OUT_ANIMATION, PATH_OUT_ANIMATION, mOutList);
        dealAssetData(NvAsset.ASSET_ANIMATED_STICKER_ANIMATION, PATH_PERIOD_ANIMATION, mPeriodList);
//        Bundle arguments = getArguments();
//        if (arguments != null) {
//            String periodAnimationId = arguments.getString("periodAnimationId");
//            String outAnimationId = arguments.getString("outAnimationId");
//            String inAnimationId = arguments.getString("inAnimationId");
//            if (!TextUtils.isEmpty(periodAnimationId)) {
//                mSelectedAniPos = getSelectedPosInList(periodAnimationId, mPeriodList);
//            } else {
//                if (!TextUtils.isEmpty(inAnimationId)) {
//                    mSelectedInAniPos = getSelectedPosInList(inAnimationId, mInList);
//                }
//                if (!TextUtils.isEmpty(outAnimationId)) {
//                    mSelectedOutAniPos = getSelectedPosInList(outAnimationId, mOutList);
//                }
//            }
//        }
    }


    /**
     * 获取对应的position
     *
     * @param animationId
     * @param assetItems
     * @return
     */
    private int getSelectedPosInList(String animationId, List<AssetItem> assetItems) {
        if (TextUtils.isEmpty(animationId) || assetItems == null || assetItems.isEmpty()) return 0;
        for (int i = 0; i < assetItems.size(); i++) {
            if (TextUtils.equals(animationId, assetItems.get(i).getAsset().uuid)) {
                return i;
            }
        }
        return 0;
    }

    /**
     * 处理asset资源数据
     *
     * @param assetType int 资源类型
     * @param assetPath String 资源路径
     * @param assetList List<AssetItem> 资源列表
     */
    private void dealAssetData(int assetType, String assetPath, List<AssetItem> assetList) {
        mAssetManager.searchLocalAssets(assetType);
        mAssetManager.searchReservedAssets(assetType, assetPath);
        ArrayList<NvAsset> usableAsset = getAssetsDataList(assetType);
        String jsonBundlePath = assetPath + "/info.json";
        ArrayList<ParseJsonFile.FxJsonFileInfo.JsonFileInfo> infoLists = ParseJsonFile.readBundleFxJsonFile(getContext(), jsonBundlePath);
        if (infoLists != null) {
            for (ParseJsonFile.FxJsonFileInfo.JsonFileInfo jsonFileInfo : infoLists) {
                for (NvAsset asset : usableAsset) {
                    if (asset == null)
                        continue;
                    if (TextUtils.isEmpty(asset.uuid))
                        continue;
                    if (asset.isReserved && asset.uuid.equals(jsonFileInfo.getFxPackageId())) {
                        if (Utils.isZh()) {
                            asset.name = jsonFileInfo.getName_Zh();
                        } else {
                            asset.name = jsonFileInfo.getName();
                        }
                        if (!TextUtils.isEmpty(jsonFileInfo.getFitRatio())) {
                            try {
                                asset.aspectRatio = Integer.parseInt(jsonFileInfo.getFitRatio());
                            } catch (Exception e) {
                                Log.e(TAG, "Exception=" + e);
                                return;
                            }
                        }
                        StringBuilder coverPath = new StringBuilder();
                        coverPath.append("asset://android_asset/");
                        coverPath.append(assetPath);
                        coverPath.append("/");
                        coverPath.append(jsonFileInfo.getImageName());
                        asset.coverUrl = coverPath.toString();
                    }
                }
            }
        }
        if (assetList == null) {
            return;
        }
        AssetItem firstItem = new AssetItem();
        NvAsset firstAsset = new NvAsset();
        firstAsset.name = getString(R.string.timeline_fx_none);
        firstItem.setImageRes(R.mipmap.square_clear);
        firstItem.setAssetMode(AssetItem.ASSET_NONE);
        firstItem.setAsset(firstAsset);
        assetList.add(firstItem);
        for (NvAsset asset : usableAsset) {
            if (asset == null)
                continue;
            if (TextUtils.isEmpty(asset.uuid))
                continue;
            if ((curRatio & asset.aspectRatio) == 0) {
                /*
                 * 制作比例不适配，不加载
                 * Production proportions do not fit, do not load
                 * */
                continue;
            }
            AssetItem assetItem = new AssetItem();
            assetItem.setAsset(asset);
            assetItem.setAssetMode(AssetItem.ASSET_LOCAL);
            assetList.add(assetItem);
        }
    }

    /*
     * 获取下载到手机路径下的素材，包括assets路径下自带的素材
     * Get the material downloaded to the mobile phone path,
     * including the material that comes with the assets path
     * */
    private ArrayList<NvAsset> getAssetsDataList(int assetType) {
        return mAssetManager.getUsableAssets(assetType, NvAsset.AspectRatio_All, 0);
    }

    private void initView() {
        mTabAnimation = findViewById(R.id.tab_animation);
        mRvAnimationList = findViewById(R.id.rv_list_animation);
        stickerSeekbar = findViewById(R.id.sticker_style_seek_bar);
        ivFinish = findViewById(R.id.iv_animation_finish);
    }

    @Override
    public void onRemoteAssetsChanged(boolean hasNext) {
        //refresh
        ArrayList<NvAsset> arrayList = mAssetManager.getRemoteAssetsWithPage(mAssetType, NvAsset.AspectRatio_All, 0, 1, 20);
        mAssetDataList = arrayList;
//        int ratio = TimelineData.instance().getMakeRatio();
//        for (NvAsset asset : arrayList) {
//            if (asset == null)
//                continue;
//            if (TextUtils.isEmpty(asset.uuid))
//                continue;
//            if ((ratio & asset.aspectRatio) == 0) {
//                /*
//                 * 制作比例不适配，不加载
//                 * Production proportions do not fit, do not load
//                 * */
//                continue;
//            }
//            AssetItem assetItem = new AssetItem();
//            assetItem.setAsset(asset);
//            assetItem.setAssetMode(AssetItem.ASSET_LOCAL);
//            mInList.add(assetItem);
//            mAnimationAdapter.setAssetList(mInList);
//            mAnimationAdapter.notifyDataSetChanged();
//        }

    }

    @Override
    public void onRemoteAssetsChanged(List<NvAsset> assetDataList, boolean hasNext) {

    }

    @Override
    public void onGetRemoteAssetsFailed() {

    }

    @Override
    public void onDownloadAssetProgress(String uuid, int progress) {
        if (getContext() != null) {
            getContext().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mAnimationAdapter.updateItemProgress(uuid, progress);
                }
            });
        }

    }

    @Override
    public void onDonwloadAssetFailed(String uuid) {

    }

    @Override
    public void onDonwloadAssetSuccess(String uuid) {
        if (getContext() != null) {
            getContext().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mAnimationAdapter.updateItemProgress(uuid, -1);
                }
            });
        }

    }

    @Override
    public void onFinishAssetPackageInstallation(String uuid) {

    }

    @Override
    public void onFinishAssetPackageUpgrading(String uuid) {

    }


    class AnimationAdapter extends RecyclerView.Adapter<AnimationAdapter.ViewHolder> {
        private List<AssetItem> mAssetList = new ArrayList<>();
        private Context mContext;
        private OnItemClickListener mOnItemClickListener = null;
        private int mSelectedPos = 0;

        AnimationAdapter(Context context) {
            mContext = context;
        }

        void setAssetList(List<AssetItem> assetArrayList) {
            this.mAssetList = assetArrayList;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(mContext).inflate(R.layout.item_animation_caption, parent, false);
            return new ViewHolder(v);
        }

        public AssetItem getSelectedItem() {
            if (mAssetList == null || mSelectedPos < 0 || mSelectedPos > mAssetList.size())
                return null;
            return mAssetList.get(mSelectedPos);
        }

        public void setSelectedPos(int selectedPos) {
            if (selectedPos == mSelectedPos) {
                return;
            }
            if (selectedPos >= 0 && mAssetList != null && selectedPos < mAssetList.size()) {
                notifyItemChanged(mSelectedPos);
                this.mSelectedPos = selectedPos;
                notifyItemChanged(mSelectedPos);
            }
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, final int position) {
            AssetItem assetItem = mAssetList.get(position);
            if (assetItem == null)
                return;
            NvAsset asset = assetItem.getAsset();
            if (asset == null)
                return;
            if (assetItem.getAssetMode() == AssetItem.ASSET_NONE) {
                holder.mIvCover.setImageResource(assetItem.getImageRes());
            } else {
                loadWebpImage(holder.mIvCover, asset.coverUrl);
            }

            holder.mTvName.setText(asset.name);
            holder.vSelected.setVisibility(mSelectedPos == position ? View.VISIBLE : View.GONE);
            holder.mTvName.setTextColor(mSelectedPos == position ? mContext.getResources().getColor(R.color.red_ff64)
                    : mContext.getResources().getColor(R.color.white));
            DownloadButtonInfo buttonInfo = getDownloadButtonInfo(asset);
            holder.mDownloadButton.setBackgroundResource(buttonInfo.buttonBackgroud);
            holder.mDownloadButton.setText(buttonInfo.buttonText);
            holder.mDownloadButton.setTextColor(Color.parseColor(buttonInfo.buttonTextColor));
            holder.mDownloadProgressBar.setVisibility(View.GONE);
            holder.mDownloadButton.setVisibility(View.VISIBLE);
            if (asset.downloadStatus == NvAsset.DownloadStatusFailed) {
                holder.mDownloadButton.setText(R.string.retry);
                holder.mDownloadButton.setTextColor(Color.parseColor("#ffffffff"));
                holder.mDownloadButton.setBackgroundResource(R.drawable.download_button_shape_corner_retry);
                holder.mDownloadProgressBar.setVisibility(View.GONE);
                holder.mDownloadButton.setVisibility(View.VISIBLE);
            } else if (asset.downloadStatus == NvAsset.DownloadStatusFinished) {
                holder.mDownloadProgressBar.setVisibility(View.GONE);
                holder.mDownloadButton.setVisibility(View.VISIBLE);
            } else if (asset.downloadStatus == NvAsset.DownloadStatusInProgress) {
                holder.mDownloadProgressBar.setVisibility(View.VISIBLE);
                holder.mDownloadProgressBar.setProgress(asset.downloadProgress);
                holder.mDownloadButton.setVisibility(View.GONE);
            }
            holder.mDownloadButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (curRatio >= AspectRatio_16v9) {
                        if ((curRatio & asset.aspectRatio) == 0) {
                            /*
                             * 时间线比例不适配，禁止下载
                             * Timeline proportions do not fit, download is prohibited
                             * */
                            return;
                        }
                    }

                    if (asset.isUsable() && !asset.hasUpdate())
                        return;
                    if (asset.isUsable() && asset.hasRemoteAsset() && asset.hasUpdate()) {
                        File file = new File(asset.localDirPath);
                        if (file.exists()) {
                            file.delete();
                        }
                    }
                    mAssetManager.downloadAsset(mAssetType, mAssetDataList.get(position).uuid);
                }
            });
        }

        public void loadWebpImage(SimpleDraweeView view, String imageUrl) {
            DraweeController controller = Fresco.newDraweeControllerBuilder()
                    .setUri(imageUrl)
                    .setAutoPlayAnimations(true)
                    .setOldController(view.getController())
                    .build();
            view.setController(controller);
        }

        public void updateItemProgress(String uuid, int progress) {
            if (mAssetDataList != null) {
                for (int index = 0; index < mAssetDataList.size(); ++index) {
                    if (mAssetDataList.get(index).uuid == uuid) {
                        if (progress >= 0) {
                            mAssetDataList.get(index).downloadProgress = progress;
                        }
                        notifyItemChanged(index);
                        break;
                    }
                }
            }
        }

        @Override
        public int getItemCount() {
            return mAssetList == null ? 0 : mAssetList.size();
        }

        public void setOnItemClickListener(OnItemClickListener itemClickListener) {
            this.mOnItemClickListener = itemClickListener;
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            SimpleDraweeView mIvCover;
            View vSelected;
            TextView mTvName;
            Button mDownloadButton;
            DownloadProgressBar mDownloadProgressBar;

            ViewHolder(View itemView) {
                super(itemView);
                mIvCover = itemView.findViewById(R.id.iv_cover);
                vSelected = itemView.findViewById(R.id.v_select);
                mTvName = itemView.findViewById(R.id.tv_name);
                mDownloadButton = (Button) itemView.findViewById(R.id.download_button);
                mDownloadProgressBar = (DownloadProgressBar) itemView.findViewById(R.id.downloadProgressBar);
                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mOnItemClickListener != null)
                            mOnItemClickListener.onItemClick(v, getAdapterPosition());
                    }
                });
            }
        }
    }


    public class DownloadButtonInfo {
        int buttonBackgroud;
        String buttonText;
        String buttonTextColor;

        public DownloadButtonInfo() {

        }
    }

    public DownloadButtonInfo getDownloadButtonInfo(NvAsset asset) {
        DownloadButtonInfo buttonInfo = new DownloadButtonInfo();
        if (curRatio >= AspectRatio_16v9 && (curRatio & asset.aspectRatio) == 0) {
            buttonInfo.buttonBackgroud = R.drawable.download_button_shape_corner_finished;
            buttonInfo.buttonText = getContext().getResources().getString(R.string.asset_mismatch);
            buttonInfo.buttonTextColor = "#ff928c8c";
        } else if (!asset.isUsable() && asset.hasRemoteAsset()) {
            buttonInfo.buttonBackgroud = R.drawable.download_button_shape_corner_download;
            buttonInfo.buttonText = getContext().getResources().getString(R.string.asset_download);
            buttonInfo.buttonTextColor = "#ffffffff";
        } else if (asset.isUsable() && !asset.hasUpdate()) {
            buttonInfo.buttonBackgroud = R.drawable.download_button_shape_corner_finished;
            buttonInfo.buttonText = getContext().getResources().getString(R.string.asset_downloadfinished);
            buttonInfo.buttonTextColor = "#ff909293";
        } else if (asset.isUsable() && asset.hasRemoteAsset() && asset.hasUpdate()) {
            buttonInfo.buttonBackgroud = R.drawable.download_button_shape_corner_update;
            buttonInfo.buttonText = getContext().getResources().getString(R.string.asset_update);
            buttonInfo.buttonTextColor = "#ffffffff";
        }
        return buttonInfo;
    }

}
